﻿using System.Collections.Generic;
using UnityEngine;
using System;
using System.Xml;
using System.Reflection;

public class ConfigLoadManager : MonoBehaviour {

    /// <summary>
    /// 加载XML数据
    /// </summary>
    /// <typeparam name="T">表名</typeparam>
    /// <returns></returns>
    public static List<T> Load<T>() where T : new()
    {
        string[] names = (typeof(T)).ToString().Split('.');
        string filename = names[names.Length - 1];
        XmlDocument doc = new XmlDocument();
        try
        {
            //打开xml配置文件
            doc.Load(ConfigEditor.xmlPath + "/" + filename + ".xml");
        }
        catch
        {
            Debug.LogError("------读取" + filename + "配置文件错误------>");
        }
        XmlNode xmlNode = doc.DocumentElement;

        XmlNodeList xnl = xmlNode.ChildNodes;
        List<T> ret = new List<T>();
        foreach (XmlNode xn in xnl)
        {
            if (xn.Name == filename)
            {
                T obj = new T();
                Type t = obj.GetType();
                FieldInfo[] fields = t.GetFields();
                string msg = "";
                try
                {
                    foreach (FieldInfo field in fields)
                    {
                        string val = xn.Attributes[field.Name].Value;
                        if (val == null)
                        {
                            Debug.Log("the field [" + field.Name + "] is null !!!");
                            continue;
                        }
                        
                        if (field.FieldType == typeof(int))
                        {
                            field.SetValue(obj, int.Parse(val));
                        }
                        else if (field.FieldType == typeof(float))
                        {
                            field.SetValue(obj, float.Parse(val));
                        }
                        else if (field.FieldType == typeof(string))
                        {
                            field.SetValue(obj, val);
                        }

                    }
                    ret.Add(obj);
                }
                catch (Exception e)
                {
                    Debug.LogError("--------------->" + filename + " error<---------------");
                    Debug.LogError(e.Message);
                    Debug.LogError(msg);
                }

            }
        }
        return ret;
    }

}
